package com.etc.controller;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.etc.entity.User;
import com.etc.service.impl.UserServiceImpl;
import com.etc.util.MD5Utile;
import com.etc.util.PageData;
import com.google.gson.Gson;


/**
 * Servlet implementation class UserController
 */
@WebServlet("/UserController")
@MultipartConfig
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}
	UserServiceImpl service = new UserServiceImpl();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取参数 参数名op的值如果等于query才做查询
		String op = request.getParameter("op");
		//提升:加入session的判断:从session中获取用户登录的信息,如果有,才能执行查询,添加等等的操作
		HttpSession session = request.getSession();
		Object object = session.getAttribute("backUser");
		if (object != null) {
			adminOp(op,request,response,session);
		}else if ("login".equals(op)) {
			//管理员登录
			Login(request,response);
		}else if("checkName".equals(op)) {
			//普通用户验证用户名是否可用
			checkName(op,request,session,response);
		}else if("register".equals(op)) {
			//普通用户注册
			register(op,request,session,response);
		}else if("createCode".equals(op)) {
			//用户注册验证码
			createCode(request,response);
		}else if("checkCode".equals(op)) {
			//用户数输入的验证码是否和随机生成的验证码相同
			checkCode(op,request,response);
		}else if ("frontLogin".equals(op)) {
			frontLogin(request,response);
		}else if ("frontUserClose".equals(op)) {
			frontUserClose(request,response);
		}else if ("frontUpdateUser".equals(op)) {
			frontUpdateUser(request,response);
		}else {
			//访问的时候发现没有登录,跳转到登陆页面去
			response.sendRedirect("back/login.jsp");
		}
	}
	private void frontUpdateUser(HttpServletRequest request, HttpServletResponse response) {
				//接受参数
				String jsonString= request.getParameter("user");
				//获取java对象
				Gson gson =new Gson();
				User user = gson.fromJson(jsonString,User.class);
				//调用修改方法
				boolean flag = service.frontUpdateUser(user);
				//返回数据
				String jsonFlag=gson.toJson(flag);
				try {
					response.getWriter().print(jsonFlag);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					response.getWriter().close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		
	}

	private void frontUserClose(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute("frontUser");
		try {
			response.sendRedirect("front/login.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void frontLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//登录
		response.setContentType("text/html;charset=utf-8");
		//得到用户输入的用户名和密码
		User user= new User();
		String userName=request.getParameter("Username");
		String userPwd=request.getParameter("Password");
		//调用业务层登录方法
		user = service.userLogin(userName);
		if (user!=null) {
			//用户名和密码正确
			//只有管理员登录才能访问后台管理界面
			boolean check = MD5Utile.DecodeByMD5(userPwd, user.getU_password());
			if (check && user.getU_status()==1 && user.getU_level()==1) {
				//判断用户是否记住密码
				String reme=request.getParameter("remember-me");
				if (reme!=null) {
					System.out.println("用户选择记住密码"+reme);
					//存
					Cookie cookie1=new Cookie("username", userName);
					Cookie cookie2 = new Cookie("userpwd", userPwd);
					Cookie cookie3 = new Cookie("checked", "checked");
					//设置cookie过期时间
					cookie1.setMaxAge(240);//单位:秒  4分钟
					cookie2.setMaxAge(240);
					cookie3.setMaxAge(240);

					response.addCookie(cookie1);
					response.addCookie(cookie2);
					response.addCookie(cookie3);
				}

				//提升->加入访问控制:登录成功后要将用户登录信息存储在session中
				HttpSession session = request.getSession();
				session.setAttribute("frontUser", user);
				//跳转到后台管理界面
				request.getRequestDispatcher("front/index.jsp").forward(request, response);
			}else {
				//用户名和密码错误,跳转登录界面:1.转发2.重定向
				response.getWriter().print("<script>alert('用户名或密码错误');location.href='front/login.jsp'</script>");
			}
		}else {
			//用户名和密码错误,跳转登录界面:1.转发2.重定向
			response.getWriter().print("<script>alert('用户名不存在');location.href='front/login.jsp'</script>");
		}
	}

	/**
	 * 管理员退出登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void Exit(HttpServletRequest request, HttpServletResponse response) {
		//设置编码格式
		response.setContentType("text/html;charset=utf-8");
		request.getSession().removeAttribute("backUser");
		try {
			response.getWriter().print("<script>alert('退出成功');location.href='back/login.jsp'</script>");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 管理员注册
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void Sign(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String usertel = request.getParameter("usertel");
		String sex = request.getParameter("sex");
		int userlevel = Integer.parseInt(request.getParameter("userlevel"));
		int userstatus = Integer.parseInt(request.getParameter("userstatus"));
		User user = new User(username, password, usertel, sex, userlevel, userstatus);
		boolean flag = service.addUser(user);
		if (flag) {
			response.sendRedirect("back/user-information.jsp");
		}
	}

	/**
	 * 验证用户名是否存在
	 * @param op
	 * @param request
	 * @param session
	 * @param response
	 * @throws IOException 
	 * @author zww
	 * 
	 */
	private void checkName(String op, HttpServletRequest request,HttpSession session,HttpServletResponse response) throws IOException {
		//设置字符格式编码
		response.setContentType("text/html;charset=utf-8");
		// 获取用户名
		String uname = request.getParameter("uname");
		//调用判断用户名的方法
		boolean flag = service.userNameCheck(uname);
		if (flag) {
			response.getWriter().print("<font color='green'>可用</font>");			
		}else {
			response.getWriter().print("<font color='red'>用户名已存在</font>");
		}

	}
	/**
	 * 普通用户注册
	 * @param op
	 * @param request
	 * @param session
	 * @param response
	 * @throws ServletException 
	 * @exception
	 * @author zww
	 */
	public void register(String op, HttpServletRequest request, HttpSession session, HttpServletResponse response) throws IOException, ServletException {
		//设置编码格式
		response.setContentType("text/html;charset=utf-8");
		//获取用户名
		String uname = request.getParameter("userName");
		System.out.println(uname);
		//密码
		String upwd = request.getParameter("userPwd");
		//手机号
		String utel = request.getParameter("utel");
		//性别
		String usex = request.getParameter("sex");
		//接收文件组件
		Part part=request.getPart("uimg");
		//是否有上传文件
		if(part.getSize()==0) {
			//调用业务层添加用户
			service.addUser(new User(uname, upwd, utel, usex, 1, 1, null));
			//注册成功前往首页		
			//response.getWriter().print("<script>alert('注册成功');location.href='front/login.jsp'</script>");
			request.getRequestDispatcher("front/login.jsp").forward(request, response);

		}else {  //有上传头像
			//创建目录,文件存储位置
			File file = new File("D:\\temp");
			if (!file.exists()) {
				//创建目录
				file.mkdir();
			}
			//3.获取文件的真实名
			//通过请求头获取文件真实名
			String header = part.getHeader("content-disposition");
			String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
			System.out.println("文件的真实名"+realName);

			//为了文件名重复,在文件名前面计入UUID唯一标志符
			UUID uuid = UUID.randomUUID();
			String newrealName=uuid+realName;

			//4.文件全路径
			String filePath="D:\\temp\\"+newrealName;
			//5.真正将文件写入本地
			part.write(filePath);
			//调用注册方法
			boolean flag = service.register(uname, upwd, utel, usex, newrealName);
			if (flag) {
				//注册成功前往首页
				//response.getWriter().print("<script>alert('注册成功');location.href='front/login.jsp'</script>");
				request.getRequestDispatcher("front/login.jsp").forward(request, response);
			}

		}


	}
	/**
	 * 生成验证码
	 * @param request
	 * @param response
	 * @throws IOException
	 * @author zww 
	 */
	public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//设置字符格式编码
		response.setContentType("text/html;charset=utf-8");

		int width=80;
		int height=30;

		//1.创建一个对象，在内存中代表一个图片（验证码图片对象）
		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); //rgb表示三原色的图片（红、绿、蓝）

		//2.美化图片
		//2.1 填充背景色
		Graphics g = image.getGraphics(); //画笔对象 (fill()/draw())
		g.setColor(Color.PINK);//设置画笔颜色
		//填充
		g.fillRect(0, 0, width-1, height-1);

		//2.2话边框
		g.setColor(Color.RED);
		g.drawRect(0, 0, width, height);

		//让验证码随机生成
		String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

		//生成随机角标
		Random ran=new Random();
		//存放生成的验证码
		String authCode=""; 
		//循环生成验证码
		for(int i=1;i<=4;i++) {
			int index = ran.nextInt(str.length()); //index为随机角标
			//获取字符
			char ch = str.charAt(index);
			//2.3写验证码
			g.drawString(ch+"", width/5*i, height/2);			
			authCode+=ch;

		}
		//将生成的验证码放在session中
		request.getSession().setAttribute("authCode", authCode);

		//2.4 给验证码图片画干扰线
		g.setColor(Color.BLACK);
		//随机生成坐标点
		for(int i=1;i<=6;i++) {
			int x1 = ran.nextInt(width);
			int x2 = ran.nextInt(width);

			int y1 = ran.nextInt(width);
			int y2 = ran.nextInt(width);
			g.drawLine(x1, y1, x2, y2);
		}


		//3.将图片输出到页面显示
		ImageIO.write(image, "jpg", response.getOutputStream()); //response输出流，目标是浏览器

	}
	/**
	 * 验证用户输入的验证码是否正确
	 * @param op
	 * @param request
	 * @param response
	 * @throws IOException
	 * @author zww
	 */
	public void checkCode(String op, HttpServletRequest request, HttpServletResponse response) throws IOException {
		//设置字符格式编码
		response.setContentType("text/html;charset=utf-8");
		//1.获取用户输入的验证码
		String inputCode = request.getParameter("checkNum");
		/*System.out.println("用户输入"+inputCode);*/

		//2.获取存放在session中的验证码
		String sessionCode=(String) request.getSession().getAttribute("authCode");
		/*System.out.println("随机生成"+sessionCode);*/

		//3.判断两个验证码是否相等,不区分大小写
		if(inputCode!=null && inputCode.toLowerCase().equals(sessionCode.toLowerCase())) {
			response.getWriter().print("<font color='green'>验证通过</font>");
		}else {
			response.getWriter().print("<font color='red'>验证码错误</font>");
		}

	}


	/**
	 * 管理员登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void Login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//登录
		response.setContentType("text/html;charset=utf-8");
		//得到用户输入的用户名和密码
		User user= new User();
		String userName=request.getParameter("uname");
		String userPwd=request.getParameter("upwd");
		//调用业务层登录方法
		user = service.userLogin(userName);
		if (user!=null) {
			//用户名和密码正确
			//只有管理员登录才能访问后台管理界面
			boolean check = MD5Utile.DecodeByMD5(userPwd, user.getU_password());
			if (check && user.getU_status()==1 && user.getU_level()==2) {
				//判断用户是否记住密码
				String reme=request.getParameter("remember-me");
				if (reme!=null) {
					System.out.println("用户选择记住密码"+reme);
					//存
					Cookie cookie1=new Cookie("username", userName);
					Cookie cookie2 = new Cookie("userpwd", userPwd);
					Cookie cookie3 = new Cookie("checked", "checked");
					//设置cookie过期时间
					cookie1.setMaxAge(240);//单位:秒  4分钟
					cookie2.setMaxAge(240);
					cookie3.setMaxAge(240);

					response.addCookie(cookie1);
					response.addCookie(cookie2);
					response.addCookie(cookie3);
				}

				//提升->加入访问控制:登录成功后要将用户登录信息存储在session中
				HttpSession session = request.getSession();
				session.setAttribute("backUser", user);
				//跳转到后台管理界面
				request.getRequestDispatcher("back/index.jsp").forward(request, response);
			}else {
				//用户名和密码错误,跳转登录界面:1.转发2.重定向
				response.getWriter().print("<script>alert('用户名或密码错误');location.href='back/login.jsp'</script>");
			}
		}else {
			//用户名和密码错误,跳转登录界面:1.转发2.重定向
			response.sendRedirect("back/login.jsp");
		}

	}
	/**
	 * 管理员操作
	 * @param op
	 * @param request
	 * @param response
	 * @param session
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void adminOp(String op, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
		if("userByPage_ajax".equals(op)) {
			userByPage_ajax(op, request, response,session);
		}else if("checkName".equals(op)) {
			//普通用户验证用户名是否可用
			checkName(op,request,session,response);
		}else if ("sign".equals(op)) {
			//管理员注册
			Sign(request,response,session);
		}else if("deleteUser".equals(op)) {
			deleteUser(op, request, response,session);
		}else if("updateUser".equals(op)) {
			updateUser(op, request, response,session);
		}else if("queryUserByLike".equals(op)) {
			queryUserByLike(op, request, response,session);
		}else if ("exit".equals(op)) {
			//管理员退出登录
			Exit(request,response);
		}

	}

	private void queryUserByLike(String op, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		// TODO Auto-generated method stub

	}
	/**
	 * 修改用户信息
	 * @param op
	 * @param request
	 * @param response
	 * @param session
	 */
	private void updateUser(String op, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		//接受参数
		String jsonString= request.getParameter("user");
		//获取java对象
		Gson gson =new Gson();
		User user = gson.fromJson(jsonString,User.class);
		//调用修改方法
		boolean flag = service.updateUser(user);
		//返回数据
		String jsonFlag=gson.toJson(flag);
		try {
			response.getWriter().print(jsonFlag);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			response.getWriter().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	/**
	 * 删除用户(修改其状态为禁止:0)
	 * @param op
	 * @param request
	 * @param response
	 * @param session
	 */
	private void deleteUser(String op, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		//接受用户删除的用户Id
		int u_id=Integer.parseInt(request.getParameter("u_id"));
		//调用service删除
		boolean flag=service.deleteUser(u_id);
		Gson gson=new Gson();
		String jsonFlag=gson.toJson(flag);
		try {
			response.getWriter().print(jsonFlag);
			response.getWriter().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 分页显示用户信息
	 * @param op
	 * @param request
	 * @param response
	 * @param session
	 */
	private void userByPage_ajax(String op, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		//设置查询默认值  用户未选择是默认第一页且查询所有
		int pageNo=1;
		int pageSize=10;
		String titleLike="";
		//如果用户选择了数据 则修改数据否则按照 默认数据处理
		if(request.getParameter("pageNo")!=null) {
			pageNo=Integer.parseInt(request.getParameter("pageNo"));
		}
		if(request.getParameter("pageSize")!=null) {
			pageSize=Integer.parseInt(request.getParameter("pageSize"));
		}
		if(request.getParameter("titleLike")!=null) {
			titleLike=request.getParameter("titleLike");
		}
		//调用业务层获取数据
		PageData pageData = service.getUserByLikeAndLimit(pageNo, pageSize, titleLike);
		//使用ajax返回请求页面
		Gson gson =new Gson();
		String json=gson.toJson(pageData);
		try {
			response.getWriter().print(json);
			response.getWriter().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
